<template>
  -=-=-=
  <a-table :columns="columns" :data="tableData" :pagination="false">
    <template #index="{ rowIndex }">
      {{ rowIndex + 1 }}
    </template>
    <template #source="{ record }">
      {{ getIndexSourceName(record.source) }}
    </template>
    <template #type="{ record }">
      <template v-if="record.type">
        {{ record.type === 1 ? '定性指标' : '定量指标' }}
      </template>
    </template>
    <template #polarity="{ record }">
      <template v-if="record.polarity">
        {{ record.polarity === 1 ? '越大越好' : '越小越好' }}
      </template>
    </template>
    <template #maxScore>
      {{ upperLimitScore ? upperLimitScore : '无限' }}
    </template>
    <template #scorer="{ rowIndex }">
      <!-- <div v-if="tableData[rowIndex].scorer">
        {{ getScorerName(tableData[rowIndex].scorer) }}
      </div> -->
      <a-space v-if="tableData[rowIndex].scorer" wrap>
        <template v-for="user in tableData[rowIndex].scorer" :key="user.id">
          <a-tag
            v-if="user.type !== 5"
            color="arcoblue"
            :default-checked="true"
          >
            {{ user.userName }}
          </a-tag>
        </template>
      </a-space>
      <div v-else>--</div>
    </template>
    <template #optional="{ record, rowIndex }">
      <a-tooltip content="编辑">
        <IconFont
          type="icon-edit"
          :size="26"
          :style="{
            marginRight: '10px',
            cursor: 'pointer'
          }"
          @click="goEdit(record, rowIndex)"
        />
      </a-tooltip>
      <a-tooltip content="设置评分人">
        <icon-user-add
          :size="24"
          style="color: #3c6eff"
          @click="setHuman(record, rowIndex)"
        />
      </a-tooltip>
      <a-tooltip content="删除" position="left">
        <a-popconfirm content="是否确认删除该条数据?" @ok="del(rowIndex)">
          <icon-font
            type="icon-delete"
            :size="26"
            :style="{
              cursor: 'pointer',
              marginRight: '10px'
            }"
          />
        </a-popconfirm>
      </a-tooltip>
    </template>
  </a-table>
  <a-button v-if="!props.review" type="text" @click="add">新增指标</a-button>
  <IndexDrawer
    v-model:visible="drawerVisible"
    @submit="submit"
    :data="currData"
  />
  <ScoreHumanModal
    v-model:visible="humanVisible"
    v-model:data="currHumanData"
    @save="saveHUman"
    @del="delHUman"
    :type="1"
    :indexType="3"
  />
</template>

<script setup lang="ts">
import { cloneDeep } from 'lodash';
import { PerformanceKeyPerformanceIndexLibraryUse } from '@/apis/management/performance/baseSetting/template/type';
import IndexDrawer from './IndexDrawer.vue';
import WeightInfo from '../AbilityIndeTable/WeightInfo.vue';
import { PersonnelAbilityQualityIndexLibrary } from '@/apis/human/base/variationManager/probation/type';
import ScoreHumanModal from '../AbilityIndeTable/ScoreHumanModal.vue';
import { delExamineToolInfo } from '@/apis/human/base/variationManager/probation';
import { useVModel } from '@vueuse/core';
import { getIndexSourceName } from '@/utils/probation';

const props = withDefaults(
  defineProps<{
    review?: boolean;
    data?: PerformanceKeyPerformanceIndexLibraryUse[];
    upperLimitScore?: number;
  }>(),
  {
    data: () => []
  }
);
const emit = defineEmits(['update:visible', 'handleOk', 'update:data']);
const tableData = useVModel(props, 'data', emit);

const handleOk = () => {
  emit('handleOk');
};
const change = () => {
  emit('update:data', tableData.value);
};

const columns = ref<any>([
  {
    title: '序号',
    dataIndex: '',
    slotName: 'index',
    width: 80
  },
  {
    title: '指标来源',
    dataIndex: 'source',
    slotName: 'source',
    width: 150
  },
  {
    title: '指标类型',
    dataIndex: 'type',
    slotName: 'type',
    width: 150
  },
  {
    title: '指标名称',
    dataIndex: 'name',
    width: 150
  },
  {
    title: '指标定义',
    dataIndex: 'indexDefinition',
    width: 200
  },
  {
    title: '项目界定',
    dataIndex: 'projectDefinition',
    width: 200
  },
  {
    title: '指标极性',
    dataIndex: 'polarity',
    slotName: 'polarity',
    width: 150
  },
  {
    title: '指标公式/说明',
    dataIndex: 'instructions',
    width: 200
  },
  {
    title: '评分标准/规则',
    dataIndex: 'rule',
    width: 200
  },
  {
    title: '考核目标',
    dataIndex: 'referenceValue',
    children: [
      {
        title: '考核基准值',
        dataIndex: 'referenceValue',
        width: 120
      },
      {
        title: '考核目标值',
        dataIndex: 'targetValue',
        width: 120
      },
      {
        title: '考核挑战值',
        dataIndex: 'challengePoint',
        width: 120
      }
    ]
  },
  {
    title: '评分上限',
    dataIndex: 'maxScore',
    slotName: 'maxScore',
    width: 100
  },
  {
    title: '指标权重',
    dataIndex: 'indexWeight',
    width: 200
  },
  {
    title: '录入/评分人',
    dataIndex: 'scorer',
    slotName: 'scorer',
    width: 400
  }
]);

const currData = ref<PerformanceKeyPerformanceIndexLibraryUse>({});
const drawerVisible = ref(false);
const editIndex = ref(-1); //编辑项的下标，用以判断新增和编辑，下标小于0是新增数据。大于等于0则是修改此下标的值
const add = () => {
  editIndex.value = -1;
  currData.value = {};
  drawerVisible.value = true;
};

const goEdit = (
  data: PerformanceKeyPerformanceIndexLibraryUse,
  index: number
) => {
  editIndex.value = index;
  currData.value = data;
  drawerVisible.value = true;
};
const submit = (data: PerformanceKeyPerformanceIndexLibraryUse) => {
  //判断是新增还是编辑
  if (editIndex.value < 0) {
    //新增
    tableData.value?.push(data);
  } else {
    //编辑
    if (!tableData.value?.length) return;

    tableData.value[editIndex.value] = data;
  }
  change();
};
onMounted(() => {
  if (!props.review) {
    columns.value.push({
      title: '操作',
      dataIndex: 'optional',
      slotName: 'optional',
      width: 150,
      align: 'center',
      fixed: 'right'
    });
  }
  tableData.value = cloneDeep(props.data);
});

const humanVisible = ref(false);
const currHumanData = ref<PersonnelAbilityQualityIndexLibrary>();
const currentIndex = ref(0);
const setHuman = (data: PersonnelAbilityQualityIndexLibrary, index: number) => {
  data.scorer = data.scorer ? data.scorer : [];
  data.scorerStatus = data.scorerStatus || {
    appoint: { status: 2, weight: 0 },
    superiors: { status: 2, weight: 0 },
    junior: { status: 2, weight: 0 },
    peer: { status: 2, weight: 0 },
    other: { status: 2, weight: 0 }
  };

  console.log('data', data);
  humanVisible.value = true;
  currentIndex.value = index;
  currHumanData.value = cloneDeep(data);
};
const saveHUman = () => {
  if (!tableData.value?.length) return;
  tableData.value[currentIndex.value] = currHumanData.value;
  humanVisible.value = false;
};
const delHUman = () => {
  if (!tableData.value?.length) return;
  tableData.value[currentIndex.value] = currHumanData.value;
  // humanVisible.value = false;
};
const del = async (index: number) => {
  console.log('index', index);

  if (!tableData.value?.length) return;
  const { id } = tableData.value[index];
  if (id > 0) {
    await delExamineToolInfo({ ids: [id], type: 3 });
  }
  tableData.value.splice(index, 1);
  // change();
};
const getScorerName = (arr: any[]) => {
  if (!Array.isArray(arr) || !arr.length) return '--';
  let newArr: any[] = [];
  arr.forEach((user) => {
    if (user.type === 5) return;
    newArr.push(user.userName);
  });
  return newArr.join(',') || '--';
};
</script>

<style lang="less" scoped>
//
</style>
